import React, { useState, useEffect } from 'react';
import { Button, Modal, Form, Select, message } from 'antd';
import { defaultProps } from '../schema';
import { getModelengine, getModeFields } from '../../preview/web/services';
import { useForm } from '@formily/react';
import { TextWidget, getMessage } from '@inbiz/react';

type IProps = {
  callBackEvents?: { [key in `on${string}`]: Function };
  emit?: (type: any, ...arg: any) => void;
  onChange?: Function;
  value?: any;
} & typeof defaultProps;

const SettingView = (props: IProps) => {
  const oldValue = props.value;
  const form = useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [models, $models] = useState([]);
  const [refIds, $refId] = useState([]);
  const [ids, $id] = useState([]);
  const [selectedModelKey, $selectedModelKey] = useState(oldValue.modelKey || null);
  const [selectedRefIds, $selectedRefIds] = useState(oldValue.RefId || null);
  const [selectedId, $selectedId] = useState(oldValue.id || null);
  useEffect(() => {
    const fetchData = async () => {
      const result = await getModelengine(form.appInfo.appId, {});
      const modelOption = [];
      result.forEach((item) => {
        modelOption.push({
          label: item.ModelName,
          value: item.ModelKey,
        });
      });
      $models(modelOption);
    };
    fetchData();
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      if (!selectedModelKey) {
        return;
      }
      const result = await getModeFields(form.appInfo.appId, {
        modelKeys: selectedModelKey,
        includeSystem: false,
      });
      const flieds = result[0]?.Fields || [];
      const idsOption = [];
      const refIdsOption = [];
      flieds.forEach((item) => {
        const opt = {
          label: item.Name,
          value: item.Name,
        };
        refIdsOption.push(opt);
        idsOption.push(opt);
      });
      $id(idsOption);
      $refId(refIdsOption);
    };
    fetchData();
  }, [selectedModelKey]);

  const showModal = () => {
    // 此处获取对应eform示例框的对应的数据
    if (!form.fields['form.senior.soure.x-component-props.sourceModel']?.value) {
      message.warn(getMessage('Tree.tips.pleaseConfigureTheQueryDataSourceFirst'));
      return;
    }
    setIsModalVisible(true);
  };

  const handleOk = () => {
    props.onChange({
      modelKey: selectedModelKey,
      RefId: selectedRefIds,
      id: selectedId,
    });
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <>
      <Button type="primary" onClick={showModal}>
        <TextWidget>config</TextWidget>
      </Button>
      <Modal
        title={getMessage('Tree.storageConfiguration')}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={900}
        destroyOnClose={true}
        isMove
      >
        <Form labelCol={{ span: 6 }} wrapperCol={{ span: 8 }}>
          <Form.Item label={getMessage('Tree.model')}>
            <Select
              options={models}
              value={selectedModelKey}
              onChange={$selectedModelKey}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item label="RefId">
            <Select
              options={refIds}
              value={selectedRefIds}
              onChange={$selectedRefIds}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item label="Id">
            <Select
              options={ids}
              value={selectedId}
              onChange={$selectedId}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default SettingView;
